package com.dao.jdbc.dao;

import java.util.List;

import com.bean.Customer;
import com.dao.CustomerDao;
import com.solveit.aps.io.db.InternalDbEntityHelper;
import com.solveit.aps.io.db.InternalDbUtil;
import com.solveit.core.db2.query.DbEntityHelper;
import com.solveit.core.db2.query.builder.C;
import com.solveit.core.db2.query.builder.Query;
import com.solveit.core.db2.query.builder.Query.Insert;
import com.solveit.core.db2.query.builder.Query.Update;

public class JdbcCustomerDao implements CustomerDao {

	@Override
	public int insert(Customer aObject) {
		Insert insert = InternalDbUtil.getInstance().insert(aObject);
		return aObject.getId();
	}

	@Override
	public List<Integer> insert(List<Customer> aObjects) {
		Query.Insert query = new Query.Insert(com.dao.jdbc.beans.Customer.class);
		InternalDbEntityHelper.getInstance().exec(query, aObjects);
		return null;
	}

	@Override
	public int delete(Customer aObject) {
		InternalDbUtil.getInstance().delete(aObject);
		return aObject.getId();
	}

	@Override
	public int delete(final List<Customer> aObjects) {
		DbEntityHelper.TransactionContext transContext = new DbEntityHelper.TransactionContext() {

            @Override
            public void execute(final DbEntityHelper.DbTransaction aTransaction) {
                for (Customer entity : aObjects) {
                    Query.Delete delete = new Query.Delete(com.dao.jdbc.beans.Customer.class);
                    delete.setCondition(C.eq(com.dao.jdbc.beans.Customer.ID, entity.getId()));
                    aTransaction.exec(delete);
                }
            }
        };
        InternalDbEntityHelper.getInstance().exec(transContext);
		return 0;
	}

	@Override
	public boolean deleteAll() {
		Query.Delete delete = new Query.Delete(com.dao.jdbc.beans.Customer.class);
		InternalDbEntityHelper.getInstance().exec(delete);
		return true;
	}

	@Override
	public boolean update(Customer aObject) {
		Update update = InternalDbUtil.getInstance().update(aObject);
		return true;
	}

	@Override
	public Customer find(Integer aId) {
		Query.Select query = new Query.Select(com.dao.jdbc.beans.Customer.class);
		query.setCondition(C.eq(com.dao.jdbc.beans.Customer.ID, aId));
		List<Customer> list = InternalDbEntityHelper.getInstance().exec(query);
		return list.isEmpty() ? null : list.get(0);
	}

	@Override
	public List<Customer> selectAll() {
		Query.Select query = new Query.Select(com.dao.jdbc.beans.Customer.class);
		List<Customer> list = InternalDbEntityHelper.getInstance().exec(query);
		return list;
	}

}
